package com.ice.work.moment.facade.ticket.mapper;

import com.alibaba.fastjson.JSONObject;
import com.honeybee.cloud.framework.common.mapper.BaseCovertMapper;
import com.ice.work.moment.facade.ticket.dto.CookieDTO;
import com.ice.work.moment.facade.ticket.model.Cookie;
import com.ice.work.moment.facade.ticket.param.CookieData;
import com.ice.work.moment.facade.ticket.param.CookieStoreParam;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Objects;

/**
 * @Description ParamConvertMapper
 * @Author DELL
 * @Create 2019-01-09
 * @Since 1.0.0
 */
@Mapper
@SuppressWarnings("all")
public interface CookieConvertMapper extends BaseCovertMapper {
    CookieConvertMapper INSTANCE = Mappers.getMapper(CookieConvertMapper.class);

    default BasicCookieStore toCookieStore(String cookieStr) {
        CookieStoreParam cookieStoreParam = JSONObject.parseObject(cookieStr, CookieStoreParam.class);
        BasicCookieStore cookieStore = new BasicCookieStore();
        if (Objects.isNull(cookieStoreParam)) {
            return cookieStore;
        }
        List<CookieData> clientCookieList = cookieStoreParam.getCookies();
        if (Objects.nonNull(clientCookieList)) {
            clientCookieList.stream().forEach(data -> {
                BasicClientCookie expCookie = new BasicClientCookie(data.getName(), data.getValue());
                expCookie.setDomain(data.getDomain());
                expCookie.setPath(data.getPath());
                expCookie.setSecure(data.getSecure());
                cookieStore.addCookie(expCookie);
            });
        }
        return cookieStore;
    }

    /**
     * toDTO
     *
     * @param cookie
     * @return
     */
    @Mappings({
            @Mapping(source = "cookieStore", target = "cookieStore", qualifiedByName = "toCookieStore")
    })
    CookieDTO toDTO(Cookie cookie);

}
